import streamlit as st
import os
import hashlib
import shutil
import subprocess
from datetime import datetime
from PIL import Image
import tempfile
import glob
from pathlib import Path
import re

# 设置页面配置
st.set_page_config(
    page_title="可遇 视频处理器v1.0",
    page_icon="🎬",
    layout="wide"
)

# 添加自定义CSS样式来修复视频预览的绿色背景问题
st.markdown("""
<style>
/* 修复视频预览的背景色问题 */
video {
    background-color: transparent !important;
    background: transparent !important;
}

/* 视频容器样式 */
.stVideo > div {
    background-color: transparent !important;
    background: transparent !important;
}

/* 视频播放器容器 */
.stVideo {
    background-color: transparent !important;
    background: transparent !important;
}

/* 确保视频元素本身没有背景色 */
video::-webkit-media-controls-panel {
    background-color: rgba(0, 0, 0, 0.1) !important;
}

/* 视频预览区域 */
[data-testid="stVideo"] {
    background-color: transparent !important;
    background: transparent !important;
}

/* 视频元素的直接样式 */
[data-testid="stVideo"] video {
    background-color: transparent !important;
    background: transparent !important;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>
""", unsafe_allow_html=True)

# 项目根目录
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
FFMPEG_PATH = os.path.join(ROOT_DIR, "ffmpeg/bin/ffmpeg.exe")
IMAGE_DIR = os.path.join(ROOT_DIR, "image")
VIDEO_DIR = os.path.join(ROOT_DIR, "video")
WEBM_DIR = os.path.join(ROOT_DIR, "webm")
TEMP_VIDEO_DIR = os.path.join(ROOT_DIR, "temp_videos")  # 暂存视频目录

# 确保目录存在
for dir_path in [IMAGE_DIR, VIDEO_DIR, WEBM_DIR, TEMP_VIDEO_DIR]:
    os.makedirs(dir_path, exist_ok=True)

def calculate_md5(file_path):
    """计算文件的MD5值"""
    hash_md5 = hashlib.md5()
    with open(file_path, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()

def copy_and_rename_file(uploaded_file, target_dir, original_extension):
    """复制文件到目标目录并根据MD5重命名"""
    # 创建临时文件
    with tempfile.NamedTemporaryFile(delete=False, suffix=original_extension) as tmp_file:
        tmp_file.write(uploaded_file.getvalue())
        tmp_path = tmp_file.name
    
    try:
        # 计算MD5
        md5_hash = calculate_md5(tmp_path)
        
        # 新文件名
        new_filename = f"{md5_hash}{original_extension}"
        target_path = os.path.join(target_dir, new_filename)
        
        # 复制文件
        shutil.copy2(tmp_path, target_path)
        
        return target_path, new_filename
    finally:
        # 清理临时文件
        os.unlink(tmp_path)

def convert_to_webm(video_path, alpha_image_path):
    """使用FFmpeg将MP4视频转换为带透明通道的WebM格式"""
    # 生成输出文件名（时间戳格式）
    timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
    output_filename = f"{timestamp}.webm"
    output_path = os.path.join(WEBM_DIR, output_filename)
    
    # FFmpeg命令
    # 使用灰度图片作为alpha通道
    cmd = [
        FFMPEG_PATH,
        "-i", video_path,
        "-i", alpha_image_path,
        "-filter_complex", "[0:v][1:v]alphamerge",
        "-c:v", "libvpx-vp9",
        "-pix_fmt", "yuva420p",
        "-y",  # 覆盖输出文件
        output_path
    ]
    
    try:
        # 执行FFmpeg命令
        result = subprocess.run(cmd, capture_output=True, text=True, check=True)
        return output_path, output_filename
    except subprocess.CalledProcessError as e:
        st.error(f"转换失败: {e.stderr}")
        return None, None

def merge_videos(video_paths, output_path, transition=None, size=None):
    """合并多个视频文件
    
    Args:
        video_paths: 视频文件路径列表
        output_path: 输出文件路径
        transition: 转场效果，None表示无转场
        size: 输出视频尺寸，格式为(width, height)
    """
    if not video_paths:
        return False
    
    # 创建临时文件列表
    temp_list_file = tempfile.NamedTemporaryFile(delete=False, suffix='.txt', mode='w')
    
    try:
        # 如果需要调整尺寸
        if size:
            # 创建调整尺寸后的临时文件
            resized_videos = []
            for i, video_path in enumerate(video_paths):
                temp_resized = os.path.join(tempfile.gettempdir(), f"resized_{i}_{os.path.basename(video_path)}")
                resize_cmd = [
                    FFMPEG_PATH,
                    "-i", video_path,
                    "-vf", f"scale={size[0]}:{size[1]}",
                    "-c:v", "libx264",
                    "-c:a", "copy",
                    "-y",
                    temp_resized
                ]
                subprocess.run(resize_cmd, capture_output=True, check=True)
                resized_videos.append(temp_resized)
            
            # 使用调整尺寸后的视频
            video_paths = resized_videos
        
        # 创建文件列表
        for video_path in video_paths:
            temp_list_file.write(f"file '{video_path}'\n")
        temp_list_file.close()
        
        # 构建FFmpeg命令
        cmd = [
            FFMPEG_PATH,
            "-f", "concat",
            "-safe", "0",
            "-i", temp_list_file.name,
            "-c", "copy"
        ]
        
        # 如果有转场效果，添加相应的滤镜
        if transition:
            # 这里可以根据不同的转场效果添加不同的滤镜命令
            # 由于转场效果需要重新编码，不能使用简单的concat demuxer
            pass
        
        # 添加输出文件路径
        cmd.extend(["-y", output_path])
        
        # 执行FFmpeg命令
        result = subprocess.run(cmd, capture_output=True, text=True, check=True)
        return True
    except subprocess.CalledProcessError as e:
        st.error(f"合并失败: {e.stderr}")
        return False
    finally:
        # 清理临时文件
        os.unlink(temp_list_file.name)
        
        # 清理调整尺寸的临时文件
        if size and 'resized_videos' in locals():
            for temp_file in resized_videos:
                if os.path.exists(temp_file):
                    os.unlink(temp_file)

def get_video_dimensions(video_path):
    """获取视频的尺寸"""
    cmd = [
        FFMPEG_PATH,
        "-i", video_path,
        "-hide_banner"
    ]
    
    try:
        result = subprocess.run(cmd, capture_output=True, text=True)
        # FFmpeg将信息输出到stderr
        output = result.stderr
        
        # 解析视频尺寸
        match = re.search(r'Stream.*Video.* (\d+)x(\d+)', output)
        if match:
            width = int(match.group(1))
            height = int(match.group(2))
            return (width, height)
    except Exception as e:
        st.error(f"获取视频尺寸失败: {str(e)}")
    
    return None

def get_video_duration(video_path):
    """获取视频的时长（秒）"""
    cmd = [
        FFMPEG_PATH,
        "-i", video_path,
        "-hide_banner"
    ]
    
    try:
        result = subprocess.run(cmd, capture_output=True, text=True)
        # FFmpeg将信息输出到stderr
        output = result.stderr
        
        # 解析视频时长
        match = re.search(r'Duration: (\d+):(\d+):(\d+)\.(\d+)', output)
        if match:
            hours = int(match.group(1))
            minutes = int(match.group(2))
            seconds = int(match.group(3))
            milliseconds = int(match.group(4))
            
            total_seconds = hours * 3600 + minutes * 60 + seconds + milliseconds / 100
            return total_seconds
    except Exception as e:
        st.error(f"获取视频时长失败: {str(e)}")
    
    return None

def check_video_has_audio(video_path):
    """检查视频是否包含音频流"""
    cmd = [
        FFMPEG_PATH,
        "-i", video_path,
        "-hide_banner"
    ]
    
    try:
        result = subprocess.run(cmd, capture_output=True, text=True)
        # FFmpeg将信息输出到stderr
        output = result.stderr
        
        # 检查是否有音频流
        return 'Stream #' in output and 'Audio:' in output
    except Exception as e:
        st.error(f"检查视频音频流失败: {str(e)}")
        return False

def get_temp_videos():
    """获取暂存视频列表"""
    temp_videos = []
    if os.path.exists(TEMP_VIDEO_DIR):
        for f in os.listdir(TEMP_VIDEO_DIR):
            if f.lower().endswith(('.mp4', '.avi', '.mov', '.mkv', '.webm')):
                video_path = os.path.join(TEMP_VIDEO_DIR, f)
                temp_videos.append({
                    'name': f,
                    'path': video_path,
                    'size': os.path.getsize(video_path) / (1024 * 1024),  # MB
                    'duration': get_video_duration(video_path),
                    'dimensions': get_video_dimensions(video_path)
                })
    return temp_videos

def save_to_temp_videos(source_path, custom_name=None):
    """将视频保存到暂存区（只保留最新的一个）"""
    try:
        # 先清理所有现有的暂存视频
        if os.path.exists(TEMP_VIDEO_DIR):
            for f in os.listdir(TEMP_VIDEO_DIR):
                if f.lower().endswith(('.mp4', '.avi', '.mov', '.mkv', '.webm')):
                    old_video_path = os.path.join(TEMP_VIDEO_DIR, f)
                    try:
                        os.remove(old_video_path)
                    except Exception as e:
                        st.warning(f"删除旧暂存视频失败: {f} - {str(e)}")
        
        if custom_name:
            # 使用自定义名称
            filename = custom_name
            if not filename.lower().endswith(('.mp4', '.avi', '.mov', '.mkv', '.webm')):
                filename += '.mp4'  # 默认添加mp4扩展名
        else:
            # 使用时间戳生成文件名
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            ext = os.path.splitext(source_path)[1]
            filename = f"temp_{timestamp}{ext}"
        
        dest_path = os.path.join(TEMP_VIDEO_DIR, filename)
        
        shutil.copy2(source_path, dest_path)
        return dest_path, filename
    except Exception as e:
        st.error(f"保存到暂存区失败: {str(e)}")
        return None, None

def delete_temp_video(video_path):
    """删除暂存视频"""
    try:
        if os.path.exists(video_path):
            os.remove(video_path)
            return True
        return False
    except Exception as e:
        st.error(f"删除暂存视频失败: {str(e)}")
        return False

def video_selector_component(key_prefix, title="选择视频", file_types=['mp4', 'avi', 'mov', 'mkv', 'webm'], multiple=False):
    """通用视频选择组件
    
    Args:
        key_prefix: 组件的唯一键前缀
        title: 组件标题
        file_types: 支持的文件类型
        multiple: 是否支持多选
    
    Returns:
        dict: {
            'source': 'upload' | 'temp',  # 视频来源
            'videos': [video_info, ...],  # 视频信息列表
            'temp_files': [temp_path, ...]  # 临时文件路径列表（用于清理）
        }
    """
    st.subheader(title)
    
    # 选择视频来源
    video_source = st.radio(
        "视频来源：",
        ["上传新视频", "选择上一步的视频"],
        key=f"{key_prefix}_video_source"
    )
    
    result = {
        'source': 'upload' if video_source == "上传新视频" else 'temp',
        'videos': [],
        'temp_files': []
    }
    
    if video_source == "上传新视频":
        # 上传新视频
        uploaded_videos = st.file_uploader(
            "上传视频文件",
            type=file_types,
            accept_multiple_files=multiple,
            key=f"{key_prefix}_uploader"
        )
        
        if uploaded_videos:
            if not multiple:
                uploaded_videos = [uploaded_videos]
            
            for i, video in enumerate(uploaded_videos):
                # 创建临时文件
                with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(video.name)[1]) as tmp_file:
                    tmp_file.write(video.getvalue())
                    temp_path = tmp_file.name
                
                result['temp_files'].append(temp_path)
                
                video_info = {
                    'name': video.name,
                    'path': temp_path,
                    'size': len(video.getvalue()) / (1024 * 1024),  # MB
                    'duration': get_video_duration(temp_path),
                    'dimensions': get_video_dimensions(temp_path),
                    'uploaded_file': video
                }
                result['videos'].append(video_info)
                
                # 显示视频预览
                st.success(f"已选择视频: {video.name}")
                with st.expander(f"预览 {video.name}", expanded=False):
                    st.video(video, start_time=0, width=300)
                    if video_info['duration']:
                        st.info(f"时长: {video_info['duration']:.2f} 秒")
                    if video_info['dimensions']:
                        st.info(f"尺寸: {video_info['dimensions'][0]}x{video_info['dimensions'][1]}")
    
    else:
        # 选择上一步的视频
        temp_videos = get_temp_videos()
        
        if temp_videos:
            st.write(f"共有 {len(temp_videos)} 个暂存视频")
            
            if multiple:
                # 多选模式
                selected_videos = st.multiselect(
                    "选择上一步的视频（可多选）：",
                    options=temp_videos,
                    format_func=lambda x: f"{x['name']} ({x['size']:.1f}MB)",
                    key=f"{key_prefix}_multiselect"
                )
                result['videos'] = selected_videos
                
                # 显示选中的视频预览
                for video in selected_videos:
                    with st.expander(f"预览 {video['name']}", expanded=False):
                        with open(video['path'], "rb") as f:
                            st.video(f.read(), start_time=0, width=300)
                        st.info(f"大小: {video['size']:.1f}MB")
                        if video['duration']:
                            st.info(f"时长: {video['duration']:.2f} 秒")
                        if video['dimensions']:
                            st.info(f"尺寸: {video['dimensions'][0]}x{video['dimensions'][1]}")
            
            else:
                # 单选模式
                cols = st.columns(min(3, len(temp_videos)))
                selected_video = None
                
                for i, video in enumerate(temp_videos):
                    col_idx = i % 3
                    with cols[col_idx]:
                        st.write(f"**{video['name']}**")
                        st.write(f"大小: {video['size']:.1f}MB")
                        if video['duration']:
                            st.write(f"时长: {video['duration']:.2f}秒")
                        
                        # 显示缩略图（使用视频预览）
                        with open(video['path'], "rb") as f:
                            st.video(f.read(), start_time=0, width=200)
                        
                        # 选择按钮
                        if st.button(f"选择", key=f"{key_prefix}_select_{i}", use_container_width=True):
                            selected_video = video
                            st.session_state[f"{key_prefix}_selected_video"] = video
                            st.success(f"已选择: {video['name']}")
                            st.rerun()
                
                # 显示当前选择的视频
                if f"{key_prefix}_selected_video" in st.session_state:
                    selected_video = st.session_state[f"{key_prefix}_selected_video"]
                    result['videos'] = [selected_video]
                    
                    st.subheader("当前选择的视频")
                    col1, col2 = st.columns([1, 2])
                    with col1:
                        with open(selected_video['path'], "rb") as f:
                            st.video(f.read(), start_time=0, width=250)
                    with col2:
                        st.write(f"**文件名:** {selected_video['name']}")
                        st.write(f"**大小:** {selected_video['size']:.1f}MB")
                        if selected_video['duration']:
                            st.write(f"**时长:** {selected_video['duration']:.2f}秒")
                        if selected_video['dimensions']:
                            st.write(f"**尺寸:** {selected_video['dimensions'][0]}x{selected_video['dimensions'][1]}")
        else:
            st.info("暂无暂存视频，请先上传视频或处理视频后保存到暂存区")
    
    return result

def adjust_video_speed(video_path, output_path, speed_factor=None, target_duration=None):
    """调整视频播放速度
    
    Args:
        video_path: 输入视频路径
        output_path: 输出视频路径
        speed_factor: 速度因子，大于1加速，小于1减速，None表示使用target_duration
        target_duration: 目标时长（秒），None表示使用speed_factor
    
    Returns:
        bool: 是否成功
    """
    if not os.path.exists(video_path):
        st.error(f"视频文件不存在: {video_path}")
        return False
    
    # 如果提供了目标时长，计算速度因子
    if target_duration is not None:
        # 获取原始视频时长
        original_duration = get_video_duration(video_path)
        if not original_duration:
            st.error("无法获取视频时长")
            return False
        
        # 计算速度因子
        speed_factor = original_duration / target_duration
    
    # 如果没有提供速度因子或目标时长，使用默认速度因子
    if speed_factor is None:
        speed_factor = 1.0
    
    # 检查视频是否包含音频流
    has_audio = check_video_has_audio(video_path)
    
    # 构建FFmpeg命令
    # 使用setpts滤镜调整视频速度
    video_filter = f"setpts={1/speed_factor}*PTS"
    
    # 根据是否有音频流构建不同的命令
    if has_audio:
        # 处理音频速度调整
        # 如果速度因子超出atempo范围，需要串联多个atempo
        audio_filter = ""
        remaining_factor = speed_factor
        
        while remaining_factor > 2.0:
            audio_filter += "atempo=2.0,"
            remaining_factor /= 2.0
        
        while remaining_factor < 0.5:
            audio_filter += "atempo=0.5,"
            remaining_factor *= 2.0
        
        # 添加最后一个atempo滤镜
        if 0.5 <= remaining_factor <= 2.0:
            audio_filter += f"atempo={remaining_factor}"
        
        # 构建完整的FFmpeg命令（包含音频）
        cmd = [
            FFMPEG_PATH,
            "-i", video_path,
            "-filter_complex", f"[0:v]{video_filter}[v];[0:a]{audio_filter}[a]",
            "-map", "[v]",
            "-map", "[a]",
            "-c:v", "libx264",
            "-c:a", "aac",
            "-y",
            output_path
        ]
    else:
        # 构建只处理视频的FFmpeg命令（没有音频）
        cmd = [
            FFMPEG_PATH,
            "-i", video_path,
            "-vf", video_filter,
            "-c:v", "libx264",
            "-an",  # 表示没有音频
            "-y",
            output_path
        ]
    
    try:
        # 执行FFmpeg命令
        result = subprocess.run(cmd, capture_output=True, text=True, check=True)
        return True
    except subprocess.CalledProcessError as e:
        st.error(f"调整视频速度失败: {e.stderr}")
        return False

def list_directory_files(directory, file_types=None):
    """列出指定目录中的文件
    
    Args:
        directory: 目录路径
        file_types: 文件类型列表，如 ['.mp4', '.webm']
    
    Returns:
        文件路径列表
    """
    files = []
    if os.path.exists(directory):
        for f in os.listdir(directory):
            file_path = os.path.join(directory, f)
            if os.path.isfile(file_path):
                if file_types is None or any(f.lower().endswith(ext) for ext in file_types):
                    files.append(file_path)
    return files

def delete_file_safe(file_path):
    """安全删除文件
    
    Args:
        file_path: 文件路径
    
    Returns:
        bool: 是否成功删除
    """
    try:
        if os.path.exists(file_path):
            os.remove(file_path)
            return True
        return False
    except Exception as e:
        st.error(f"删除文件失败: {str(e)}")
        return False

def segment_speed_adjust(video_path, output_path, front_seconds, back_seconds, front_speed, middle_speed, back_speed):
    """分段变速处理视频
    
    Args:
        video_path: 输入视频路径
        output_path: 输出视频路径
        front_seconds: 前段时长（秒）
        back_seconds: 后段时长（秒）
        front_speed: 前段倍速
        middle_speed: 中段倍速
        back_speed: 后段倍速
    
    Returns:
        bool: 是否成功
    """
    if not os.path.exists(video_path):
        st.error(f"视频文件不存在: {video_path}")
        return False
    
    # 获取视频总时长
    total_duration = get_video_duration(video_path)
    if not total_duration:
        st.error("无法获取视频时长")
        return False
    
    # 计算中段时长
    middle_seconds = total_duration - front_seconds - back_seconds
    if middle_seconds <= 0:
        st.error("前段和后段时长之和不能大于等于视频总时长")
        return False
    
    # 检查视频是否包含音频流
    has_audio = check_video_has_audio(video_path)
    
    try:
        # 创建临时文件用于存储各段视频
        temp_dir = tempfile.mkdtemp()
        front_temp = os.path.join(temp_dir, "front.mp4")
        middle_temp = os.path.join(temp_dir, "middle.mp4")
        back_temp = os.path.join(temp_dir, "back.mp4")
        
        # 分割视频为三段
        # 前段 (0 到 front_seconds)
        front_cmd = [
            FFMPEG_PATH,
            "-i", video_path,
            "-t", str(front_seconds),
            "-c:v", "libx264",
            "-c:a", "aac" if has_audio else "-an",
            "-y", front_temp
        ]
        
        # 中段 (front_seconds 到 front_seconds + middle_seconds)
        middle_cmd = [
            FFMPEG_PATH,
            "-i", video_path,
            "-ss", str(front_seconds),
            "-t", str(middle_seconds),
            "-c:v", "libx264",
            "-c:a", "aac" if has_audio else "-an",
            "-y", middle_temp
        ]
        
        # 后段 (从 front_seconds + middle_seconds 到结束)
        back_start = front_seconds + middle_seconds
        back_cmd = [
            FFMPEG_PATH,
            "-i", video_path,
            "-ss", str(back_start),
            "-c:v", "libx264",
            "-c:a", "aac" if has_audio else "-an",
            "-y", back_temp
        ]
        
        # 执行分割命令
        try:
            # 分割前段
            result = subprocess.run(front_cmd, capture_output=True, text=True, check=True)
            if not os.path.exists(front_temp) or os.path.getsize(front_temp) == 0:
                st.error(f"前段视频分割失败: {result.stderr}")
                return False
            
            # 分割中段
            result = subprocess.run(middle_cmd, capture_output=True, text=True, check=True)
            if not os.path.exists(middle_temp) or os.path.getsize(middle_temp) == 0:
                st.error(f"中段视频分割失败: {result.stderr}")
                return False
            
            # 分割后段
            result = subprocess.run(back_cmd, capture_output=True, text=True, check=True)
            if not os.path.exists(back_temp) or os.path.getsize(back_temp) == 0:
                st.error(f"后段视频分割失败: {result.stderr}")
                return False
                
        except subprocess.CalledProcessError as e:
            st.error(f"视频分割失败: {e.stderr}")
            return False
        
        # 对各段进行变速处理
        front_speed_temp = os.path.join(temp_dir, "front_speed.mp4")
        middle_speed_temp = os.path.join(temp_dir, "middle_speed.mp4")
        back_speed_temp = os.path.join(temp_dir, "back_speed.mp4")
        
        # 处理前段变速
        if not adjust_video_speed(front_temp, front_speed_temp, front_speed):
            return False
        
        # 处理中段变速
        if not adjust_video_speed(middle_temp, middle_speed_temp, middle_speed):
            return False
        
        # 处理后段变速
        if not adjust_video_speed(back_temp, back_speed_temp, back_speed):
            return False
        
        # 合并三段视频
        merge_success = merge_videos([front_speed_temp, middle_speed_temp, back_speed_temp], output_path)
        
        # 清理临时文件
        shutil.rmtree(temp_dir)
        
        return merge_success
        
    except subprocess.CalledProcessError as e:
        st.error(f"分段变速处理失败: {e.stderr}")
        # 清理临时文件
        if 'temp_dir' in locals():
            shutil.rmtree(temp_dir, ignore_errors=True)
        return False
    except Exception as e:
        st.error(f"调整视频速度失败: {str(e)}")
        # 清理临时文件
        if 'temp_dir' in locals():
            shutil.rmtree(temp_dir, ignore_errors=True)
        return False

def main():
    st.title("🎬 视频工具箱")
    
    # 创建选项卡
    tab1, tab2, tab3, tab4, tab5 = st.tabs(["1️⃣ 视频合并", "2️⃣ 视频倍速调整", "3️⃣ 视频分段变速", "4️⃣ 视频加透明通道", "5️⃣ 文件管理"])
    

    
    with tab1:
        st.header("🎬 视频合并工具")
        st.markdown("将多个视频合并成一个视频文件")
        
        # 创建两列布局
        col1, col2 = st.columns(2)
        
        with col1:
            # 使用新的视频选择组件
            video_selection = video_selector_component(
                key_prefix="merge",
                title="📹 选择要合并的视频",
                file_types=['mp4', 'avi', 'mov', 'mkv', 'webm'],
                multiple=True
            )
            
            selected_videos = video_selection['videos']
            
            if selected_videos:
                st.success(f"已选择 {len(selected_videos)} 个视频文件")
                
                # 显示选择的视频列表
                st.subheader("已选择的视频")
                for i, video in enumerate(selected_videos):
                    st.write(f"{i+1}. {video['name']}")
                    if video.get('duration'):
                        st.write(f"   时长: {video['duration']:.2f}秒")
                    if video.get('dimensions'):
                        st.write(f"   尺寸: {video['dimensions'][0]}x{video['dimensions'][1]}")
        
        with col2:
            # 合并选项
            st.subheader("合并选项")
            
            # 转场效果选择
            transition = st.selectbox(
                "转场效果",
                ["无转场", "淡入淡出", "擦除"],
                index=0,
                key="transition_effect"
            )
            
            # 是否调整视频尺寸
            adjust_size = st.checkbox("统一视频尺寸（按第一个视频）", value=True, key="adjust_size")
            
            # 输出文件名
            output_filename = st.text_input("输出文件名", value=f"merged_{datetime.now().strftime('%Y%m%d%H%M%S')}.mp4", key="output_filename")
        
        # 合并按钮
        if st.button("🚀 开始合并", type="primary", use_container_width=True, key="merge_button"):
            if not selected_videos or len(selected_videos) < 2:
                st.error("请至少选择两个视频文件！")
            else:
                with st.spinner("正在处理文件..."):
                    try:
                        # 获取视频路径列表
                        temp_video_paths = [video['path'] for video in selected_videos]
                        
                        # 确定输出路径
                        output_path = os.path.join(VIDEO_DIR, output_filename)
                        
                        # 获取第一个视频的尺寸（如果需要调整尺寸）
                        size = None
                        if adjust_size and temp_video_paths:
                            size = get_video_dimensions(temp_video_paths[0])
                            if size:
                                st.info(f"将所有视频调整为 {size[0]}x{size[1]} 尺寸")
                        
                        # 转场效果映射
                        transition_effect = None
                        if transition != "无转场":
                            transition_effect = transition
                        
                        # 执行视频合并
                        success = merge_videos(temp_video_paths, output_path, transition_effect, size)
                        
                        if success and os.path.exists(output_path):
                            st.success(f"✅ 合并成功！输出文件: {output_filename}")
                            
                            # 保存到暂存区
                            temp_path, temp_filename = save_to_temp_videos(output_path, f"merged_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4")
                            if temp_path:
                                st.info(f"📁 已保存到暂存区: {temp_filename}")
                            
                            # 显示合并后的视频预览
                            st.subheader("🎥 合并结果预览")
                            with open(output_path, 'rb') as f:
                                video_bytes = f.read()
                            st.video(video_bytes, start_time=0, width=400)
                            
                            # 提供下载链接
                            st.download_button(
                                label="📥 下载合并后的视频",
                                data=video_bytes,
                                file_name=output_filename,
                                mime="video/mp4"
                            )
                        else:
                            st.error("❌ 合并失败，请检查视频格式和FFmpeg配置")
                    
                    except Exception as e:
                        st.error(f"处理失败: {str(e)}")
                    finally:
                        # 清理临时文件（只清理上传的临时文件）
                        for temp_path in video_selection['temp_files']:
                            if os.path.exists(temp_path):
                                os.unlink(temp_path)

    with tab2:
        st.header("🎬 视频倍速调整工具")
        st.markdown("调整视频的播放速度，可以按倍速调整或按目标时长调整")
        
        # 使用新的视频选择组件
        video_selection = video_selector_component(
            key_prefix="speed",
            title="📹 选择要调整倍速的视频",
            file_types=['mp4', 'avi', 'mov', 'mkv', 'webm'],
            multiple=False
        )
        
        selected_videos = video_selection['videos']
        
        if selected_videos:
            video_info = selected_videos[0]  # 单选模式，只有一个视频
            input_video_path = video_info['path']
            
            st.success(f"已选择视频: {video_info['name']}")
            
            # 获取原始视频时长
            original_duration = video_info.get('duration') or get_video_duration(input_video_path)
            if original_duration:
                st.info(f"原始视频时长: {original_duration:.2f} 秒")
            
            # 创建两列布局
            col1, col2 = st.columns(2)
            
            with col1:
                # 调整方式选择
                adjustment_method = st.radio(
                    "调整方式",
                    ["按倍速调整", "按目标时长调整"],
                    key="adjustment_method"
                )
                
                # 根据选择的调整方式显示不同的输入控件
                speed_factor = None
                target_duration = None
                
                if adjustment_method == "按倍速调整":
                    speed_factor = st.slider(
                        "速度倍数",
                        min_value=0.1,
                        max_value=5.0,
                        value=1.0,
                        step=0.1,
                        key="speed_factor"
                    )
                    
                    if original_duration:
                        st.info(f"调整后预计时长: {original_duration/speed_factor:.2f} 秒")
                else:  # 按目标时长调整
                    if original_duration:
                        target_duration = st.number_input(
                            "目标时长（秒）",
                            min_value=1.0,
                            max_value=original_duration * 10,
                            value=original_duration,
                            step=1.0,
                            key="target_duration"
                        )
                        
                        # 计算对应的速度倍数
                        calculated_speed = original_duration / target_duration
                        st.info(f"对应的速度倍数: {calculated_speed:.2f}x")
            
            with col2:
                # 输出文件名
                output_filename = st.text_input(
                    "输出文件名",
                    value=f"speed_{datetime.now().strftime('%Y%m%d%H%M%S')}.mp4",
                    key="speed_output_filename"
                )
                
                # 输出格式选择
                output_format = st.selectbox(
                    "输出格式",
                    ["MP4", "AVI", "MKV", "WebM"],
                    index=0,
                    key="output_format"
                )
                
                # 确保文件名有正确的扩展名
                file_base = os.path.splitext(output_filename)[0]
                if output_format == "MP4":
                    output_filename = f"{file_base}.mp4"
                elif output_format == "AVI":
                    output_filename = f"{file_base}.avi"
                elif output_format == "MKV":
                    output_filename = f"{file_base}.mkv"
                elif output_format == "WebM":
                    output_filename = f"{file_base}.webm"
            
            # 调整按钮
            if st.button("🚀 开始调整速度", type="primary", use_container_width=True, key="adjust_speed_button"):
                try:
                    # 确定输出路径
                    output_path = os.path.join(VIDEO_DIR, output_filename)
                    
                    with st.spinner("正在调整视频速度..."):
                        # 调用函数调整视频速度
                        if adjustment_method == "按倍速调整":
                            success = adjust_video_speed(input_video_path, output_path, speed_factor=speed_factor)
                        else:  # 按目标时长调整
                            success = adjust_video_speed(input_video_path, output_path, target_duration=target_duration)
                        
                        if success and os.path.exists(output_path):
                            st.success(f"✅ 调整成功！输出文件: {output_filename}")
                            
                            # 显示调整后的视频预览
                            st.subheader("🎥 调整结果预览")
                            with open(output_path, 'rb') as f:
                                video_bytes = f.read()
                            st.video(video_bytes, start_time=0, width=400)
                            
                            # 保存到暂存区
                            if adjustment_method == "按倍速调整":
                                temp_filename = f"倍速调整_{speed_factor}x_{video_info['name']}"
                            else:
                                temp_filename = f"时长调整_{target_duration}s_{video_info['name']}"
                            save_to_temp_videos(output_path, temp_filename)
                            st.info(f"✅ 视频已保存到暂存区: {temp_filename}")
                            
                            # 提供下载链接
                            st.download_button(
                                label="📥 下载调整后的视频",
                                data=video_bytes,
                                file_name=output_filename,
                                mime=f"video/{output_format.lower()}"
                            )
                        else:
                            st.error("❌ 调整失败，请检查视频格式和FFmpeg配置")
                
                except Exception as e:
                    st.error(f"处理失败: {str(e)}")
                finally:
                    # 清理临时文件（如果是上传的文件）
                    if video_info.get('is_uploaded', False) and os.path.exists(input_video_path):
                        os.unlink(input_video_path)

    with tab3:
        st.header("🎬 视频分段变速")
        st.markdown("对视频的前段、中段、后段分别设置不同的播放倍速")
        
        # 使用新的视频选择组件
        video_selection = video_selector_component(
            key_prefix="segment",
            title="📹 选择要进行分段变速的视频",
            file_types=['mp4', 'avi', 'mov', 'mkv', 'webm'],
            multiple=False
        )
        
        selected_videos = video_selection['videos']
        
        if selected_videos:
            video_info = selected_videos[0]  # 单选模式，只有一个视频
            input_video_path = video_info['path']
            
            st.success(f"已选择视频: {video_info['name']}")
            
            # 获取原始视频时长
            original_duration = video_info.get('duration') or get_video_duration(input_video_path)
            if original_duration:
                st.info(f"原始视频时长: {original_duration:.2f} 秒")
                
                # 创建三列布局用于设置参数
                col1, col2, col3 = st.columns(3)
                
                with col1:
                    st.subheader("⏪ 前段设置")
                    front_seconds = st.number_input(
                        "前段时长（秒）",
                        min_value=0.1,
                        max_value=original_duration * 0.8,
                        value=min(5.0, original_duration * 0.2),
                        step=0.1,
                        key="front_seconds"
                    )
                    
                    front_speed = st.slider(
                        "前段倍速",
                        min_value=0.1,
                        max_value=5.0,
                        value=1.0,
                        step=0.1,
                        key="front_speed"
                    )
                    
                    st.info(f"前段调整后时长: {front_seconds/front_speed:.2f} 秒")
                
                with col2:
                    st.subheader("⏸️ 中段设置")
                    back_seconds = st.number_input(
                        "后段时长（秒）",
                        min_value=0.1,
                        max_value=original_duration * 0.8,
                        value=min(5.0, original_duration * 0.2),
                        step=0.1,
                        key="back_seconds"
                    )
                    
                    # 计算中段时长
                    middle_seconds = original_duration - front_seconds - back_seconds
                    if middle_seconds > 0:
                        st.info(f"中段时长: {middle_seconds:.2f} 秒")
                        
                        middle_speed = st.slider(
                            "中段倍速",
                            min_value=0.1,
                            max_value=5.0,
                            value=1.0,
                            step=0.1,
                            key="middle_speed"
                        )
                        
                        st.info(f"中段调整后时长: {middle_seconds/middle_speed:.2f} 秒")
                    else:
                        st.error("前段和后段时长之和不能大于等于视频总时长")
                        middle_speed = 1.0
                
                with col3:
                    st.subheader("⏩ 后段设置")
                    st.info(f"后段时长: {back_seconds:.2f} 秒")
                    
                    back_speed = st.slider(
                        "后段倍速",
                        min_value=0.1,
                        max_value=5.0,
                        value=1.0,
                        step=0.1,
                        key="back_speed"
                    )
                    
                    st.info(f"后段调整后时长: {back_seconds/back_speed:.2f} 秒")
                
                # 输出设置
                st.subheader("📤 输出设置")
                output_col1, output_col2 = st.columns(2)
                
                with output_col1:
                    output_filename = st.text_input(
                        "输出文件名",
                        value=f"segment_speed_{datetime.now().strftime('%Y%m%d%H%M%S')}.mp4",
                        key="segment_output_filename"
                    )
                
                with output_col2:
                    # 显示预计总时长
                    if middle_seconds > 0:
                        total_new_duration = (front_seconds/front_speed) + (middle_seconds/middle_speed) + (back_seconds/back_speed)
                        st.info(f"预计总时长: {total_new_duration:.2f} 秒")
                
                # 处理按钮
                if st.button("🚀 开始分段变速处理", type="primary", use_container_width=True, key="segment_speed_button"):
                    if middle_seconds <= 0:
                        st.error("请调整前段和后段时长，确保中段时长大于0")
                    else:
                        try:
                            # 确定输出路径
                            output_path = os.path.join(VIDEO_DIR, output_filename)
                            
                            with st.spinner("正在进行分段变速处理..."):
                                # 调用分段变速函数
                                success = segment_speed_adjust(
                                    input_video_path, 
                                    output_path, 
                                    front_seconds, 
                                    back_seconds, 
                                    front_speed, 
                                    middle_speed, 
                                    back_speed
                                )
                                
                                if success and os.path.exists(output_path):
                                    st.success(f"✅ 分段变速处理成功！输出文件: {output_filename}")
                                    
                                    # 显示处理后的视频预览
                                    st.subheader("🎥 处理结果预览")
                                    with open(output_path, 'rb') as f:
                                        video_bytes = f.read()
                                    st.video(video_bytes, start_time=0, width=400)
                                    
                                    # 保存到暂存区
                                    temp_filename = f"分段变速_{front_speed}x_{middle_speed}x_{back_speed}x_{video_info['name']}"
                                    save_to_temp_videos(output_path, temp_filename)
                                    st.info(f"✅ 视频已保存到暂存区: {temp_filename}")
                                    
                                    # 提供下载链接
                                    st.download_button(
                                        label="📥 下载处理后的视频",
                                        data=video_bytes,
                                        file_name=output_filename,
                                        mime="video/mp4"
                                    )
                                else:
                                    st.error("❌ 分段变速处理失败，请检查视频格式和FFmpeg配置")
                        
                        except Exception as e:
                            st.error(f"处理失败: {str(e)}")
                        finally:
                            # 清理临时文件（如果是上传的文件）
                            if video_info.get('is_uploaded', False) and os.path.exists(input_video_path):
                                os.unlink(input_video_path)
            else:
                st.warning("无法获取视频时长，请检查视频文件格式")
        else:
            st.info("请上传视频文件开始分段变速处理")

    with tab4:
        st.header("🎬 添加透明通道")
        st.markdown("将MP4视频转换为带透明通道的WebM格式")
        
        # 创建两列布局
        col1, col2 = st.columns(2)
    
        with col1:
            st.header("📹 选择MP4视频")
            
            # 使用新的视频选择组件
            video_selection = video_selector_component(
                key_prefix="transparent",
                title="📹 选择要添加透明通道的MP4视频",
                file_types=['mp4'],
                multiple=False
            )
            
            selected_videos = video_selection['videos']
            
            if selected_videos:
                video_info = selected_videos[0]  # 单选模式，只有一个视频
                st.success(f"已选择视频: {video_info['name']}")
        
        with col2:
            st.header("🖼️ 选择灰度图片")
            
            # 获取已有的图片文件列表
            existing_images = []
            if os.path.exists(IMAGE_DIR):
                for f in os.listdir(IMAGE_DIR):
                    if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.tiff')):
                        existing_images.append(f)
            
            # 选择图片的方式
            image_source = st.radio(
                "选择图片来源：",
                ["选择已有的灰度图", "上传新图片"],
                key="image_source"
            )
            
            image_file = None
            selected_image_path = None
            
            if image_source == "上传新图片":
                image_file = st.file_uploader(
                    "上传灰度图片文件（作为透明通道）",
                    type=['png', 'jpg', 'jpeg', 'bmp', 'tiff'],
                    key="image_uploader"
                )
                
                if image_file is not None:
                    st.success(f"已选择图片: {image_file.name}")
                    
                    # 显示图片预览
                    st.subheader("图片预览")
                    image = Image.open(image_file)
                    st.image(image, caption=img_file, width=100)
            
            else:  # 从已有图片中选择
                if existing_images:
                    st.write("选择已有的灰度图片：")
                    
                    # 使用列表形式显示图片，支持点击预览
                    cols = st.columns(min(8, len(existing_images)))  # 最多3列
                
                    for i, img_file in enumerate(existing_images):
                        col_idx = i % 8
                        with cols[col_idx]:
                            img_path = os.path.join(IMAGE_DIR, img_file)
                            
                            # 显示图片缩略图
                            try:
                                image = Image.open(img_path)
                                st.image(image, caption=img_file, width=100)
                                
                                # 选择按钮
                                if st.button(f"选择 {img_file}", key=f"select_{img_file}", use_container_width=True):
                                    selected_image_path = img_path
                                    st.session_state.selected_image = img_file
                                    st.success(f"已选择图片: {img_file}")
                                    st.rerun()
                            except Exception as e:
                                st.error(f"无法加载图片 {img_file}: {str(e)}")
                    
                    # 显示当前选择的图片预览
                    if 'selected_image' in st.session_state and st.session_state.selected_image:
                        selected_image_path = os.path.join(IMAGE_DIR, st.session_state.selected_image)
                        if os.path.exists(selected_image_path):
                            st.subheader("当前选择的图片")
                            image = Image.open(selected_image_path)
                            st.image(image, caption=f"选择的灰度图片: {st.session_state.selected_image}", width=300)
                else:
                    st.warning("暂无已保存的图片文件，请先上传图片。")
        
        # 转换按钮
        if st.button("🚀 开始转换", type="primary", use_container_width=True):
            # 检查是否选择了视频和图片
            has_selected_image = 'selected_image' in st.session_state and st.session_state.selected_image
            has_image = (image_file is not None) or has_selected_image
            
            if not selected_videos or not has_image:
                st.error("请先选择视频文件和图片文件！")
            else:
                with st.spinner("正在处理文件..."):
                    try:
                        # 获取视频路径
                        video_path = video_info['path']
                        video_filename = video_info['name']
                        st.info(f"使用视频文件: {video_filename}")
                        
                        # 处理图片文件
                        if image_file is not None:
                            # 上传的新图片
                            image_ext = os.path.splitext(image_file.name)[1]
                            image_path, image_filename = copy_and_rename_file(
                                image_file, IMAGE_DIR, image_ext
                            )
                            st.info(f"图片文件已保存为: {image_filename}")
                        elif has_selected_image:
                            # 使用已有图片
                            image_path = os.path.join(IMAGE_DIR, st.session_state.selected_image)
                            image_filename = st.session_state.selected_image
                            st.info(f"使用已有图片: {image_filename}")
                        else:
                            st.error("未找到选择的图片文件")
                            return
                        
                    except Exception as e:
                        st.error(f"文件处理失败: {str(e)}")
                        return
                
                with st.spinner("正在转换视频..."):
                    # 执行视频转换
                    output_path, output_filename = convert_to_webm(video_path, image_path)
                    
                    if output_path and os.path.exists(output_path):
                        st.success(f"✅ 转换成功！输出文件: {output_filename}")
                        
                        # 显示转换后的WebM视频预览
                        st.subheader("🎥 转换结果预览")
                        with open(output_path, 'rb') as f:
                            video_bytes = f.read()
                        st.video(video_bytes, start_time=0, width=400)
                        
                        # 保存到暂存区
                        temp_filename = f"透明通道_{video_info['name']}.webm"
                        save_to_temp_videos(output_path, temp_filename)
                        st.info(f"✅ 视频已保存到暂存区: {temp_filename}")
                        
                        # 提供下载链接
                        st.download_button(
                            label="📥 下载WebM文件",
                            data=video_bytes,
                            file_name=output_filename,
                            mime="video/webm"
                        )
                    else:
                        st.error("❌ 转换失败，请检查文件格式和FFmpeg配置")
    
    # MP4转WebM页面底部结束
    
    with tab5:
        st.header("📁 文件管理器")
        st.markdown("管理image、video和webm目录中的文件，支持预览、删除和下载")
        
        # 创建选项卡选择不同的目录
        dir_tab1, dir_tab2, dir_tab3 = st.tabs(["🖼️ 图片文件", "🎬 视频文件", "🎞️ WebM文件"])
        
        with dir_tab1:
            st.subheader("图片文件管理")
            
            # 上传新图片
            uploaded_image = st.file_uploader(
                "上传新图片",
                type=['png', 'jpg', 'jpeg', 'bmp', 'tiff'],
                key="file_manager_image_uploader"
            )
            
            if uploaded_image is not None:
                try:
                    # 复制并重命名图片文件
                    image_ext = os.path.splitext(uploaded_image.name)[1]
                    image_path, image_filename = copy_and_rename_file(
                        uploaded_image, IMAGE_DIR, image_ext
                    )
                    st.success(f"图片文件已保存为: {image_filename}")
                    
                    # 显示图片预览
                    image = Image.open(image_path)
                    st.image(image, caption=f"上传的图片: {image_filename}", width=300)
                    
                    # 刷新页面以显示新上传的图片
                    st.rerun()
                except Exception as e:
                    st.error(f"图片处理失败: {str(e)}")
            
            # 获取并显示所有图片
            image_files = list_directory_files(IMAGE_DIR, ['.png', '.jpg', '.jpeg', '.bmp', '.tiff'])
            
            if image_files:
                st.write(f"共有 {len(image_files)} 个图片文件")
                
                # 使用列表形式显示图片
                cols = st.columns(6)  # 3列布局
                
                for i, img_path in enumerate(image_files):
                    col_idx = i % 6
                    with cols[col_idx]:
                        img_filename = os.path.basename(img_path)
                        
                        try:
                            # 显示图片
                            image = Image.open(img_path)
                            st.image(image, caption=img_filename)
                            
                            # 创建两列用于放置按钮
                            btn_col1, btn_col2 = st.columns(2)
                            
                            # 下载按钮
                            with btn_col1:
                                with open(img_path, "rb") as f:
                                    st.download_button(
                                        label="📥 下载",
                                        data=f.read(),
                                        file_name=img_filename,
                                        mime=f"image/{os.path.splitext(img_filename)[1][1:]}",
                                        key=f"download_img_{i}"
                                    )
                            
                            # 删除按钮
                            with btn_col2:
                                if st.button("🗑️ 删除", key=f"delete_img_{i}"):
                                    if delete_file_safe(img_path):
                                        st.success(f"已删除: {img_filename}")
                                        st.rerun()
                                    else:
                                        st.error(f"删除失败: {img_filename}")
                        except Exception as e:
                            st.error(f"无法加载图片 {img_filename}: {str(e)}")
            else:
                st.info("暂无图片文件")
        
        with dir_tab2:
            st.subheader("视频文件管理")
            
            # 上传新视频
            uploaded_video = st.file_uploader(
                "上传新视频",
                type=['mp4', 'avi', 'mov', 'mkv'],
                key="file_manager_video_uploader"
            )
            
            if uploaded_video is not None:
                try:
                    # 复制并重命名视频文件
                    video_ext = os.path.splitext(uploaded_video.name)[1]
                    video_path, video_filename = copy_and_rename_file(
                        uploaded_video, VIDEO_DIR, video_ext
                    )
                    st.success(f"视频文件已保存为: {video_filename}")
                    
                    # 显示视频预览
                    st.video(uploaded_video, start_time=0, width=300)
                    
                    # 刷新页面以显示新上传的视频
                    st.rerun()
                except Exception as e:
                    st.error(f"视频处理失败: {str(e)}")
            
            # 获取并显示所有视频
            video_files = list_directory_files(VIDEO_DIR, ['.mp4', '.avi', '.mov', '.mkv'])
            
            if video_files:
                st.write(f"共有 {len(video_files)} 个视频文件")
                
                # 使用列表形式显示视频
                for i, video_path in enumerate(video_files):
                    video_filename = os.path.basename(video_path)
                    
                    st.write(f"**{i+1}. {video_filename}**")
                    
                    # 创建两列布局
                    vcol1, vcol2 = st.columns([2, 1])
                    
                    with vcol1:
                        # 视频预览
                        with open(video_path, "rb") as f:
                            st.video(f.read(), start_time=0, width=300)
                    
                    with vcol2:
                        # 视频信息
                        file_size = os.path.getsize(video_path) / (1024 * 1024)  # MB
                        st.write(f"文件大小: {file_size:.2f} MB")
                        
                        # 获取视频时长
                        duration = get_video_duration(video_path)
                        if duration:
                            st.write(f"视频时长: {duration:.2f} 秒")
                        
                        # 获取视频尺寸
                        dimensions = get_video_dimensions(video_path)
                        if dimensions:
                            st.write(f"视频尺寸: {dimensions[0]}x{dimensions[1]}")
                        
                        # 下载按钮
                        with open(video_path, "rb") as f:
                            st.download_button(
                                label="📥 下载视频",
                                data=f.read(),
                                file_name=video_filename,
                                mime=f"video/{os.path.splitext(video_filename)[1][1:]}",
                                key=f"download_video_{i}"
                            )
                        
                        # 删除按钮
                        if st.button("🗑️ 删除视频", key=f"delete_video_{i}"):
                            if delete_file_safe(video_path):
                                st.success(f"已删除: {video_filename}")
                                st.rerun()
                            else:
                                st.error(f"删除失败: {video_filename}")
                    
                    st.divider()  # 添加分隔线
            else:
                st.info("暂无视频文件")
        
        with dir_tab3:
            st.subheader("WebM文件管理")
            
            # 上传新WebM文件
            uploaded_webm = st.file_uploader(
                "上传新WebM文件",
                type=['webm'],
                key="file_manager_webm_uploader"
            )
            
            if uploaded_webm is not None:
                try:
                    # 复制并重命名WebM文件
                    webm_ext = os.path.splitext(uploaded_webm.name)[1]
                    webm_path, webm_filename = copy_and_rename_file(
                        uploaded_webm, WEBM_DIR, webm_ext
                    )
                    st.success(f"WebM文件已保存为: {webm_filename}")
                    
                    # 显示WebM预览
                    st.video(uploaded_webm, start_time=0, width=300)
                    
                    # 刷新页面以显示新上传的WebM
                    st.rerun()
                except Exception as e:
                    st.error(f"WebM处理失败: {str(e)}")
            
            # 获取并显示所有WebM文件
            webm_files = list_directory_files(WEBM_DIR, ['.webm'])
            
            if webm_files:
                st.write(f"共有 {len(webm_files)} 个WebM文件")
                
                # 使用列表形式显示WebM
                for i, webm_path in enumerate(webm_files):
                    webm_filename = os.path.basename(webm_path)
                    
                    st.write(f"**{i+1}. {webm_filename}**")
                    
                    # 创建两列布局
                    wcol1, wcol2 = st.columns([2, 1])
                    
                    with wcol1:
                        # WebM预览
                        with open(webm_path, "rb") as f:
                            st.video(f.read(), start_time=0, width=300)
                    
                    with wcol2:
                        # WebM信息
                        file_size = os.path.getsize(webm_path) / (1024 * 1024)  # MB
                        st.write(f"文件大小: {file_size:.2f} MB")
                        
                        # 获取视频时长
                        duration = get_video_duration(webm_path)
                        if duration:
                            st.write(f"视频时长: {duration:.2f} 秒")
                        
                        # 获取视频尺寸
                        dimensions = get_video_dimensions(webm_path)
                        if dimensions:
                            st.write(f"视频尺寸: {dimensions[0]}x{dimensions[1]}")
                        
                        # 下载按钮
                        with open(webm_path, "rb") as f:
                            st.download_button(
                                label="📥 下载WebM",
                                data=f.read(),
                                file_name=webm_filename,
                                mime="video/webm",
                                key=f"download_webm_{i}"
                            )
                        
                        # 删除按钮
                        if st.button("🗑️ 删除WebM", key=f"delete_webm_{i}"):
                            if delete_file_safe(webm_path):
                                st.success(f"已删除: {webm_filename}")
                                st.rerun()
                            else:
                                st.error(f"删除失败: {webm_filename}")
                    
                    st.divider()  # 添加分隔线
            else:
                st.info("暂无WebM文件")

if __name__ == "__main__":
    main()